<template>
    <div>
        <div v-show="isShowModal" class="opacity"><img :src="loading" alt="加载中..."></div>
        <div class="l-table">
            <ul class="list-group">
                <li class="list-group-item">
                    <span>查询历史数据</span>
                    <select v-model="searchDate" v-on:change="getData">
                        <option v-for="date in dates" v-bind:value="date">{{date}}</option>
                    </select>
                </li>
               <li class="list-group-item" style="margin-bottom: 10px;" v-for=" (router,index1) in cleanRouters">
                   <div><label style="font-size: 26px;"><a @click="toggleLine(router)" style="font-size: 18px;"><i v-bind:class="router.isActive ? ShowClass : HideClass"></i></a>{{router.Line}}</label><span class="total_line pull-right">{{router.total_Line}}</span></div>
                   <ul v-if="router.isActive" class="list-group">
                      <li class="list-group-item Xy" v-bind:class="isClick == Xy.XY ? clicked : ''" style="margin-bottom: 3px;" v-for="(Xy,index2) in router.XYs" @click="getDistanceByXY(Xy.XY)">
                          <div><span style="font-size: 18px;"><a @click="toggleXY(index1,index2)" style="font-size: 16px;"><i v-bind:class="Xy.isActive ? ShowClass : HideClass"></i></a>{{Xy.XY}}<span style="margin-left:100px;display:inline-block">{{Xy.company[0].distance}}</span></span><span class="total_XY pull-right">{{Xy.total_XY}}</span></div>
                          <ul v-if="Xy.isActive" class="list-group">
                              <li class="list-group-item" v-for="co in Xy.company">
                                  <div style="float: left">
                                      <span style="margin-right: 20px;">{{co.type}}</span>
                                      <div style="width: 300px;display: inline-block"><span>{{co.address}}</span></div>
                                      <span style="margin-right: 20px;">{{co.customer}}</span>
                                  </div>
                                  <div style="text-align: right">
                                      <span style="padding-right: -20px;">{{co.Quantity}}</span>
                                  </div>
                              </li>
                          </ul>
                      </li> 
                   </ul>
               </li> 
            </ul>
        </div>
        <div class="map">
            <div id="l-map"></div>
            <div id="r-result">
            <div id="result"></div>
        </div>
	    </div>
        
    </div>
</template>
<script>
    import BMap from 'BMap'

    export default {
        data() {
            return {
                ShowClass: 'fa fa-chevron-up',
                HideClass: 'fa fa-chevron-right',
                routers: '',
                cleanRouters: [],
                dates: [],
                searchDate: '',
                isShowModal: false,
                loading: require('../assets/imgs/loading.gif'),
                map: '',
                clicked: 'clicked',
                isClick: ''

            }
        },
        methods: {
            getDate() {
                var dates = []
                var myDate = new Date().getTime()
                for (var i = 0; i < 10; i++) {
                    myDate = myDate - 24 * 60 * 60 * 1000 * i
                    var year = new Date(parseInt(myDate)).getFullYear()
                    var month = new Date(parseInt(myDate)).getMonth() + 1
                    var date = new Date(parseInt(myDate)).getDate()
                    if (month < 10) {
                        month = '0' + String(month)
                    }
                    if (date < 10) {
                        date = '0' + String(date)
                    }
                    var fulldate = String(year) + String(month) + String(date)
                    dates.push(fulldate)
                    myDate = new Date().getTime()
                }
                this.searchDate = dates[0]
                this.dates = dates
                this.getData()
            },
            cleanRouter() {
                //清洗数据
                this.cleanRouters = []
                var routers = this.routers
                var lines = []
                for (var i = 0; i < routers.length; i++) {
                    var index = lines.indexOf(routers[i].Line)
                    if (index == -1) {
                        lines.push(routers[i].Line)
                        var obj = {}
                        obj.Line = routers[i].Line
                        obj.isActive = true
                        this.cleanRouters.push(obj)
                    }
                }
                // console.log(JSON.stringify(this.cleanRouters, null, "\t"))
                for (var x in lines) {
                    var XYs = []
                    for (var i = 0; i < this.routers.length; i++) {
                        if (this.routers[i].Line == lines[x]) {
                            XYs.push(this.routers[i].XY)
                        }
                    }
                    this.cleanRouters[x].XYs = []
                    var temp = []
                    for (var j = 0; j < XYs.length; j++) {
                        var obj = {}
                        obj.XY = XYs[j]
                        obj.isActive = true
                            // obj.xyId = x + ':' + j
                        if (temp.indexOf(obj.XY) == -1) {
                            this.cleanRouters[x].XYs.push(obj)
                            temp.push(obj.XY)
                        }
                    }
                }
                // console.log(JSON.stringify(this.cleanRouters, null, "\t"))
                for (var i = 0; i < this.cleanRouters.length; i++) {
                    this.cleanRouters[i].total_Line = 0
                    var total_Line = 0
                    for (var j = 0; j < this.cleanRouters[i].XYs.length; j++) {
                        this.cleanRouters[i].XYs[j].company = []
                        this.cleanRouters[i].XYs[j].total_XY = 0
                        var total_XY = 0
                        var company = []
                        for (var k = 0; k < this.routers.length; k++) {
                            if (this.routers[k].XY == this.cleanRouters[i].XYs[j].XY) {
                                var obj = {}
                                obj.type = this.routers[k].Type
                                obj.address = this.routers[k].Address
                                obj.customer = this.routers[k].Customer
                                obj.distance = this.routers[k].distance
                                obj.Quantity = this.routers[k].Quantity
                                company.push(obj)
                                total_XY += parseInt(obj.Quantity)
                            }
                        }
                        this.cleanRouters[i].XYs[j].company = company
                        this.cleanRouters[i].XYs[j].total_XY = total_XY
                        total_Line += this.cleanRouters[i].XYs[j].total_XY
                    }
                    this.cleanRouters[i].total_Line = total_Line
                }
                // console.log(lines)
                //console.log(JSON.stringify(this.cleanRouters, null, "\t"))
            },
            getData() {
                this.isShowModal = true
                var _this = this
                $.ajax({
                    type: 'POST',
                    url: 'http://192.168.1.66:5000/delivery/get',
                    data: {
                        'period': _this.searchDate
                            // 'period': '20170213'
                    },
                    dataType: 'json',
                    async: false,
                    crossDomain: true,
                    error: function(request) {
                        _this.$store.commit('showModal','连接错误')
                    },
                    success: function(retdata) {
                        if (retdata.message == 'fail') {
                            _this.isShowModal = false
                            _this.$store.commit('showModal','当日无数据')
                        } else {
                            _this.routers = retdata.data
                            _this.getXY()
                        }
                    }
                });
            },
            getXY() {
                // var map = new BMap.Map("l-map");
                // var point = new BMap.Point(120.543325, 31.185039);
                // map.centerAndZoom(point, 15);
                // var marker = new BMap.Marker(point); // 创建标注
                // map.addOverlay(marker); // 将标注添加到地图中
                // marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
                // 百度地图API功能
                var map = new BMap.Map("l-map");
                this.map = map;
                map.centerAndZoom(new BMap.Point(120.543325, 31.185039), 12);
                map.enableScrollWheelZoom(true);
                var point = new BMap.Point(120.543325, 31.185039);
                var marker = new BMap.Marker(point);
                map.addOverlay(marker);
                marker.setAnimation(BMAP_ANIMATION_BOUNCE);
                var index = 0;
                var myGeo = new BMap.Geocoder();
                var adds = [];
                var XY = [];
                var distance = [];
                for (var x in this.routers) {
                    adds.push(this.routers[x].Address)
                }

                function bdGEO() {
                    var add = adds[index];
                    geocodeSearch(add);
                    index++;
                }
                var _this = this

                function geocodeSearch(add) {
                    if (index < adds.length) {
                        setTimeout(function() {
                            var add = adds[index];
                            geocodeSearch(add);
                            index++;
                        }, 400);
                    } else {
                        for (var x in _this.routers) {
                            _this.routers[x].XY = XY[x]
                            _this.routers[x].distance = distance[x]
                        }
                        _this.cleanRouter()
                        _this.isShowModal = false
                    }

                    myGeo.getPoint(add, function(point) {
                        if (point) {
                            var address = new BMap.Point(point.lng, point.lat);
                            XY.push(point.lng + ',' + point.lat)
                            console.log(add + address)
                            addMarker(address, new BMap.Label(index + ":" + add));
                        }
                        getDistance(add, point)
                    }, add.substring(0, 3));

                }
                //根据起终点获取路程
                function getDistance(add, point) {

                    var searchComplete = function(results) {
                        if (transit.getStatus() != BMAP_STATUS_SUCCESS) {
                            return;
                        }
                        var plan = results.getPlan(0);
                        // console.log(add + plan.getDistance(true)) //获取距离
                        // console.log('-----------------------------')
                        distance.push(plan.getDistance(true))
                    }
                    var transit = new BMap.DrivingRoute(map, {
                        renderOptions: {
                            // map: map
                        },
                        onSearchComplete: searchComplete
                            // onPolylinesSet: function() {}
                    });
                    var start = new BMap.Point(120.543635, 31.184998); //美嘉的地址
                    var end = new BMap.Point(point.lng, point.lat);

                    transit.search(start, end);
                    transit.clearResults();

                }
                // 编写自定义函数,创建标注
                function addMarker(point, label) {
                    var marker = new BMap.Marker(point);
                    map.addOverlay(marker);
                    // map.addOverlay(marker);
                    marker.disableMassClear()
                }
                bdGEO()

            },
            toggleLine(value) {
                event.stopPropagation()
                value.isActive = !value.isActive


            },
            toggleXY(index1, index2) {
                event.stopPropagation()

                var obj = this.cleanRouters[index1]
                obj.XYs[index2].isActive = !obj.XYs[index2].isActive
                this.$set(this.cleanRouters, index1, obj)
            },
            getDistanceByXY(XY) {
                this.isClick = XY
                var map = this.map
                map.enableScrollWheelZoom();
                var xy = []
                xy = XY.split(',')
                var p1 = new BMap.Point(120.543635, 31.184998);
                var p2 = new BMap.Point(xy[0], xy[1]);

                var driving = new BMap.DrivingRoute(map, {
                    renderOptions: {
                        map: map,
                        autoViewport: true,
                    }
                });
                map.clearOverlays()
                driving.search(p1, p2);
            }
        },
        mounted() {
            this.getDate()

        }
    }
</script>
<style>
    .opacity {
        position: fixed;
        width: 100%;
        height: 100%;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background-color: #000;
        opacity: 0.7;
        z-index: 2000;
    }
    
    .opacity img {
        position: absolute;
        top: 45%;
        left: 50%;
    }
    
    .loading {
        position: fixed;
        width: 30%;
        height: 30%;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background-color: #fff;
        z-index: 2001;
    }
    
    .l-table {
        width: 50%;
        max-height: 800px;
        /*background-color: #fff;*/
        float: left;
        padding-right: 20px;
        /*padding-top: 20px;*/
        text-align: left;
        overflow: auto;
        color: #000;
    }
    
    .l-table a:hover {
        color: #333
    }
    
    .l-table .list-group {
        margin-bottom: 0;
    }
    
    .l-table .list-group-item {
        padding: 5px;
        margin-left: 30px;
    }
    
    .l-table .list-group .list-group-item .list-group .list-group-item {
        /*border: none*/
    }
    
    .total_line {
        clear: both;
        font-size: 26px;
    }
    
    .total_XY {
        clear: both;
        font-size: 18px;
    }
    
    .Xy:hover {
        border-right: 4px solid #00bfff;
        cursor: pointer;
    }
    
    .clicked {
        border-right: 4px solid #00bfff;
    }
    
    .map {
        padding-left: 5px;
        width: 50%;
        min-height: 100%;
        float: left;
    }
    
    #allmap {
        margin-top: 200px;
        width: 50%;
        height: 100%;
        margin: 0;
        font-family: "微软雅黑";
    }
    
    #l-map {
        height: 800px;
        width: 100%;
    }
    
    #r-result {
        width: 100%;
        font-size: 14px;
        line-height: 20px;
        display: none
    }
</style>